<template>
  <div>
    <!-- 订单状态切换按钮 -->
    <div style="background-color: white">
      <div class="status-buttons">
        <button
          :class="{ active: currentStatus === 'all' }"
          @click="currentStatus = 'all'"
        >
          {{ $t("myorder.statusButtons.all") }}
        </button>
        <button
          :class="{ active: currentStatus === 'unpaid' }"
          @click="currentStatus = 'unpaid'"
        >
          {{ $t("myorder.statusButtons.unpaid") }}
        </button>
        <button
          :class="{ active: currentStatus === 'unshipped' }"
          @click="currentStatus = 'unshipped'"
        >
          {{ $t("myorder.statusButtons.unshipped") }}
        </button>
        <button
          :class="{ active: currentStatus === 'unreceived' }"
          @click="currentStatus = 'unreceived'"
        >
          {{ $t("myorder.statusButtons.unreceived") }}
        </button>
        <button
          :class="{ active: currentStatus === 'completed' }"
          @click="currentStatus = 'completed'"
        >
          {{ $t("myorder.statusButtons.completed") }}
        </button>
      </div>
      <!-- 显示状态为全部订单时，用户进行搜索 -->
      <div v-if="currentStatus === 'all'" class="search-box">
        <input
          v-model="searchKeyword"
          type="text"
          :placeholder="$t('search.inputOrderPlaceholder')"
        />
        <button @click="searchOrders">{{ $t("search.buttonText") }}</button>
      </div>
    </div>
    <!-- 订单信息表格 -->
    <div class="order-list">
      <div
        v-for="order in filteredOrders"
        :key="order.orderId"
        class="order-item"
      >
        <div class="order-header">
          <span>{{ $t("myorder.orderList.orderId") }} {{ order.orderId }}</span>
          <span
            >{{ $t("myorder.orderList.orderStatus") }}
            {{ getOrderStatus(order) }}</span
          >
        </div>
        <div class="order-body">
          <div
            v-for="item in order.items"
            :key="item.productId"
            class="product-item"
          >
            <img
              :src="getProductImage(item)"
              alt="商品图片"
              class="product-image"
            />
            <div class="myorder-product-info">
              <span>{{ item.productName }}</span>
              <span>{{ $t("products.quantity") }} {{ item.quantity }}</span>
            </div>
          </div>
          <div class="order-summary">
            <span
              >{{ $t("myorder.orderList.totalPrice") }} ￥
              {{ order.totalPrice }}</span
            >
            <div class="order-actions">
              <button
                v-if="getOrderStatus(order) === '待付款'"
                @click="goToPayment(order)"
                class="handleOrder handleOrder_pay"
              >
                {{ $t("myorder.orderList.pay") }}
              </button>
              <button
                v-if="getOrderStatus(order) === '待发货'"
                class="handleOrder handleOrder_packup"
              >
                {{ $t("myorder.orderList.packup") }}
              </button>
              <button
                v-if="getOrderStatus(order) === '待收货'"
                @click="viewLogistics(order.orderId)"
                class="handleOrder handleOrder_logistics"
              >
                {{ $t("myorder.orderList.logistics") }}
              </button>
              <button
                v-if="getOrderStatus(order) === '已完成'"
                @click="handleAfterSales(order.orderId)"
                class="handleOrder handleOrder_aftersales"
              >
                {{ $t("myorder.orderList.afterSales") }}
              </button>
              <!-- 新增的“查看历史售后”按钮-->
              <button
                v-if="getOrderStatus(order) === '已完成'"
                @click="handleViewHistory(order.orderId)"
                class="handleOrder handleOrder_aftersales"
              >
                {{ $t("myorder.orderList.viewHistory") }}
              </button>
              <!-- 新增取消订单按钮 -->
              <button
                v-if="['待付款', '待发货'].includes(getOrderStatus(order))"
                @click="cancelOrder(order.orderId)"
                class="handleOrder"
              >
                {{ $t("myorder.orderList.cancelOrder") }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 申请售后弹窗 -->
    <el-dialog
      v-model="showApplyDialog"
      :title="$t('myorder.applyDialog.title')"
      width="600px"
    >
      <el-form :model="form" label-width="80px">
        <el-form-item :label="$t('myorder.applyDialog.form.saleType.label')">
          <el-select
            v-model="form.saleType"
            :placeholder="$t('myorder.applyDialog.form.saleType.placeholder')"
          >
            <el-option
              v-for="option in saleTypes"
              :key="option.value"
              :label="
                $t(`myorder.applyDialog.form.saleType.options.${option.value}`)
              "
              :value="option.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('myorder.applyDialog.form.title.label')">
          <el-input
            v-model="form.title"
            :placeholder="$t('myorder.applyDialog.form.title.placeholder')"
          />
        </el-form-item>

        <el-form-item :label="$t('myorder.applyDialog.form.description.label')">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            :placeholder="
              $t('myorder.applyDialog.form.description.placeholder')
            "
          />
        </el-form-item>

        <el-form-item :label="$t('myorder.applyDialog.form.upload.label')">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleUpload"
            :file-list="fileList"
            multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showApplyDialog = false">{{
          $t("myorder.applyDialog.form.buttons.cancel")
        }}</el-button>
        <el-button type="primary" @click="submitApplication">{{
          $t("myorder.applyDialog.form.buttons.submit")
        }}</el-button>
      </template>
    </el-dialog>

    <!-- 售后状态详情页弹窗 -->
    <el-dialog
      v-model="showStatusDialog"
      :title="$t('myorder.statusDialog.title')"
      width="600px"
    >
      <div class="status-detail">
        <!-- 售后状态步骤条 -->
        <el-steps :active="statusActive" finish-status="success">
          <el-step
            :title="$t('myorder.statusDialog.steps.submit.title')"
            :description="$t('myorder.statusDialog.steps.submit.description')"
          />
          <el-step
            :title="$t('myorder.statusDialog.steps.processing.title')"
            :description="
              $t('myorder.statusDialog.steps.processing.description')
            "
          />
          <el-step :title="statusTitle" :description="statusDescription" />
        </el-steps>

        <!-- 申请信息 -->
        <div class="application-info">
          <h4>{{ $t("myorder.statusDialog.applicationInfo.title") }}</h4>
          <p>
            <strong>{{
              $t("myorder.statusDialog.applicationInfo.saleType")
            }}</strong
            >{{ currentApplication?.saleType }}
          </p>
          <p>
            <strong>{{
              $t("myorder.statusDialog.applicationInfo.problemTitle")
            }}</strong
            >{{ currentApplication?.title }}
          </p>
          <p>
            <strong>{{
              $t("myorder.statusDialog.applicationInfo.problemDescription")
            }}</strong
            >{{ currentApplication?.description }}
          </p>
        </div>

        <!-- 图片凭证 -->
        <div class="evidence-box" v-if="currentApplication?.evidence?.length">
          <h4>{{ $t("myorder.statusDialog.evidence.title") }}</h4>
          <div class="image-grid">
            <el-image
              v-for="(img, index) in currentApplication.evidence"
              :key="index"
              :src="img.url"
              fit="cover"
              class="evidence-image"
              style="width: 528px; height: 528px"
            />
          </div>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      v-model="showHistoryDialog"
      :title="$t('myorder.historyDialog.title')"
      width="600px"
    >
      <el-table :data="afterSalesHistoryList" style="width: 100%">
        <el-table-column
          prop="applicationId"
          :label="$t('myorder.historyDialog.table.columns.applicationId')"
          width="100"
        />
        <el-table-column
          prop="productTitle"
          :label="$t('myorder.historyDialog.table.columns.productTitle')"
        />
        <el-table-column
          prop="saleType"
          :label="$t('myorder.historyDialog.table.columns.saleType')"
          width="120"
        />
        <el-table-column
          :label="$t('myorder.historyDialog.table.columns.action')"
          width="120"
        >
          <template #default="scope">
            <el-button
              size="small"
              @click="viewApplicationDetail(scope.row.applicationId)"
              >{{ $t("myorder.historyDialog.table.actions.view") }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <el-button @click="showHistoryDialog = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 物流信息弹窗 -->
    <el-dialog
      v-model="logisticsDialogVisible"
      :title="$t('myorder.logisticsDialog.title')"
      width="500"
    >
      <p>
        {{ $t("myorder.logisticsDialog.info.logisticsNo") }}
        {{ logisticsInfo.logisticsNo }}
      </p>
      <p>
        {{ $t("myorder.logisticsDialog.info.logisticsCompany") }}
        {{ logisticsInfo.logisticsCompany }}
      </p>
      <p>
        {{ $t("myorder.logisticsDialog.info.logisticsStatus") }}
        {{ logisticsInfo.logisticsStatus }}
      </p>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="logisticsDialogVisible = false">{{
            $t("myorder.logisticsDialog.buttons.close")
          }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import "../../assets/css/MyOrder.css";
import { ref, computed, reactive, onMounted } from "vue";
import {
  ElMessage,
  ElDialog,
  ElButton,
  ElInput,
  ElIcon,
  ElCol,
} from "element-plus";
import { useRouter, useRoute } from "vue-router";
import request from "@/utils/request.js";
import { Plus } from "@element-plus/icons-vue";
import axios from "axios";

const userInfo = JSON.parse(localStorage.getItem("xm-pro-user"));
const buyerid = userInfo.id;
console.log("用户ID为：", buyerid);
console.log("用户id类型为：", typeof buyerid);
const router = useRouter();
const route = useRoute();

const orders = reactive([]); // 存储订单数据
const logisticsInfo = ref({}); // 存储物流信息
const logisticsDialogVisible = ref(false); // 控制物流信息弹窗的显示与隐藏

// 在原有代码基础上新增以下内容
const showApplyDialog = ref(false);
const showStatusDialog = ref(false);
const currentOrder = ref(null);
const fileList = ref([]);
const statusActive = ref(1);
const statusTitle = ref("处理完成");
const statusDescription = ref("您的售后申请已处理完成");
const afterSalesHistoryList = ref([]); // 当前订单的所有售后记录
const showHistoryDialog = ref(false); // 控制“历史售后列表”弹窗显示

const form = reactive({
  saleType: "",
  title: "",
  description: "",
});

const saleTypes = [
  { value: "refund" },
  { value: "onlyRefund" },
  { value: "exchange" },
];

// 跳转至付款页面
const goToPayment = (order) => {
  const orderData = {
    buyerId: buyerid,
    items: {},
    adressId: order.addressId,
    orderId: order.orderId,
  };
  order.items.forEach((item) => {
    orderData.items[item.productId] = item.quantity;
  });

  const apiResponse = {
    msg: "成功",
  };

  router.push({
    path: "payment",
    name: "Payment",
    query: {
      orderData: JSON.stringify(orderData),
      apiResponse: JSON.stringify(apiResponse),
      products: JSON.stringify(order.items),
    },
  });
};

// 获取用户订单数据
const fetchOrders = () => {
  request
    .get(`/order/apid/${buyerid}`)
    .then((res) => {
      console.log("用户订单数据:", res);
      // 排序订单：按订单生成时间从最新的订单开始排序
      const sortedOrders = res.sort((a, b) => {
        return b.orderId - a.orderId;
      });
      orders.length = 0;
      orders.push(...sortedOrders);
    })
    .catch((err) => {
      console.error("获取订单数据失败", err);
      ElMessage({
        message: $t("myorder.messages.fetchOrdersFailed"),
        type: "error",
      });
    });
};

// 取消订单
const cancelOrder = (orderId) => {
  const params = {
    orderId: orderId,
    productIds: [],
  };
  request({
    method: "delete",
    url: "/order/delete",
    data: params,
  })
    .then((response) => {
      if (response) {
        ElMessage({
          message: $t("myorder.messages.cancelOrderSuccess"),
          type: "success",
        });
        fetchOrders(); // 重新获取订单数据
      } else {
        ElMessage({
          message: $t("myorder.messages.cancelOrderFailed"),
          type: "error",
        });
      }
    })
    .catch((err) => {
      console.error("取消订单失败", err);
      ElMessage({
        message: $t("myorder.messages.cancelOrderFailed"),
        type: "error",
      });
    });
};

// 获取商品的第一张图片
const getProductImage = (product) => {
  // 如果商品有多张图片，返回第一张图片
  if (product.imagePath && product.imagePath.length > 0) {
    const imageFiles = product.imagePath.split(";");
    return imageFiles.length > 0 ? `${imageFiles[0]}` : ""; // 假设图片数组是 `images`
  }
  return "";
};

// 搜索关键字
const searchKeyword = ref("");
// 搜索订单方法
const searchOrders = () => {
  // 这里已经在 computed 中实现了搜索逻辑，此方法可留空
};

// 当前选中的订单状态
const currentStatus = ref("all");
// 订单状态下拉框是否打开
const statusDropdownOpen = ref(false);
// 切换订单状态下拉框的显示与隐藏
const toggleStatusDropdown = () => {
  statusDropdownOpen.value = !statusDropdownOpen.value;
};

// 计算过滤后的订单列表
const filteredOrders = computed(() => {
  let filtered = orders;
  if (searchKeyword.value) {
    filtered = filtered.filter((order) =>
      order.orderId.toString().includes(searchKeyword.value)
    );
  }
  switch (currentStatus.value) {
    case "all":
      return filtered;
    case "unpaid":
      return filtered.filter((order) => order.orderStatus === "UNPAID");
    case "unshipped":
      return filtered.filter(
        (order) =>
          order.orderStatus === "PAID" && order.orderStatus !== "SHIPPED"
      );
    case "unreceived":
      return filtered.filter(
        (order) =>
          order.orderStatus === "SHIPPED" && order.orderStatus !== "RECEIVED"
      );
    case "completed":
      return filtered.filter((order) => order.orderStatus === "COMPLETED");
    default:
      return [];
  }
});

// 根据状态顺序获取订单的实际状态
const getOrderStatus = (order) => {
  switch (order.orderStatus) {
    case "UNPAID":
      return "待付款";
    case "PAID":
      return "待发货";
    case "SHIPPED":
      return "待收货";
    case "COMPLETED":
      return "已完成";
    default:
      return "未知状态";
  }
};

// 查看物流信息
const viewLogistics = async (orderId) => {
  try {
    const response = await request.get(`/logistics/getlogistics/${orderId}`);
    console.log("物流信息响应:", response);
    if (response.msg === "成功") {
      logisticsInfo.value = response.data;
      console.log("设置物流信息:", logisticsInfo.value); // 添加调试信息
      logisticsDialogVisible.value = true; // 显示物流信息弹窗
      console.log("设置弹窗可见:", logisticsDialogVisible.value); // 添加调试信息
    } else {
      ElMessage({
        message: $t("myorder.messages.getLogisticsFailed"),
        type: "error",
      });
    }
  } catch (err) {
    console.error("获取物流信息失败", err);
    ElMessage({
      message: $t("myorder.messages.getLogisticsFailed"),
      type: "error",
    });
  }
};

// 申请售后
// const applyAfterSales = (orderId) => {
//   // 这里可以添加申请售后的逻辑，例如跳转到售后申请页面
//   console.log(`申请订单 ${orderId} 的售后`);
//   ElMessage({
//     message: `正在申请订单 ${orderId} 的售后`,
//     type: 'info'
//   });
// };
const currentApplication = reactive({
  saleType: "",
  title: "",
  description: "",
  timestamp: "", // 用于显示时间戳
  evidence: [], // 用于显示上传的凭证
  statusStep: 0, // 当前步骤，0表示已提交，1表示处理中，2表示已完成
  finalStatus: {
    // 最终状态
    saleType: "",
    title: "",
    description: "",
  },
});
// console.log("售后类型：",currentApplication.saleType);
const handleUpload = (file, fileListRaw) => {
  fileList.value = fileListRaw;
};
const handleAfterSales = (orderId) => {
  showApplyDialog.value = true;
  currentOrder.value = orderId;
};

const submitApplication = async () => {
  const imageUrls = [];

  console.log("准备上传文件：", fileList.value);
  for (const file of fileList.value) {
    if (!file.raw) {
      console.warn("未找到 raw 文件，跳过此文件:", file);
      continue;
    }

    const formData = new FormData();
    formData.append("file", file.raw);

    try {
      const res = await request.post("/files/upload", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });

      if (res.code === "200" && res.data) {
        imageUrls.push(res.data); // 保存返回的图片 URL
      } else {
        console.warn("上传成功但返回结构异常", res);
      }
    } catch (e) {
      console.error("图片上传失败：", e);
    }
  }

  console.log("最终拼接图片链接:", imageUrls);

  const payload = {
    orderItemsId: currentOrder.value,
    productTitle: form.title,
    productDescription: form.description,
    productImages: imageUrls.join(","), // 以逗号拼接字符串
    saleType: form.saleType,
  };
  // console.log("OrderId",payload.orderId);

  request
    .post("/aftersale/apply", payload)
    .then((res) => {
      console.log("提交售后返回：", res);

      if (res.code === "200") {
        ElMessage({
          message: $t("myorder.messages.applyAfterSalesSuccess"),
          type: "success",
        });

        const match = res.data.match(/申请ID为[:：](\d+)/);
        if (match) {
          const applyId = parseInt(match[1]);
          currentOrder.value.applicationId = applyId;

          // 这里是关键，更新原订单列表
          const updatedOrder = orders.find(
            (order) => order.id === currentOrder.value
          );
          if (updatedOrder) {
            updatedOrder.applicationId = applyId;
            updatedOrder.hasAfterSalesHistory = true;
          }
        } else {
          ElMessage({
            message: $t("myorder.messages.applyIdParseFailed"),
            type: "warning",
          });
          return;
        }

        currentOrder.value.afterSalesStatus = "applied";
        currentOrder.value.application = {
          ...payload,
          status: "pending",
        };

        form.title = "";
        form.description = "";
        fileList.value = [];
        showApplyDialog.value = false;
      } else {
        ElMessage({
          message: $t("myorder.messages.applyAfterSalesFailed") + res.msg,
          type: "error",
        });
      }
    })
    .catch((err) => {
      console.error("售后申请异常", err);
      // ElMessage.error('提交售后申请失败，请稍后重试');
    });
};

// 更新售后状态显示
const updateStatusByCode = (statusCode, resultType) => {
  switch (statusCode) {
    case 0:
      statusActive.value = 1;
      statusTitle.value = "待商家处理";
      statusDescription.value = "您的申请已提交，等待商家处理";
      break;
    case 1:
      statusActive.value = 2;
      statusTitle.value = "商家处理中";
      statusDescription.value = "商家正在处理您的请求";
      break;
    case 2:
      statusActive.value = 3;
      statusTitle.value = resultType || "处理完成";
      statusDescription.value = `您的售后申请已处理完成，类型为：${resultType}`;
      break;
    default:
      statusActive.value = 1;
      statusTitle.value = "状态未知";
      statusDescription.value = "未能识别当前售后状态";
  }
};

const handleViewHistory = (orderId) => {
  request
    .get(`/aftersale/getAllStatus/${orderId}`)
    .then((res) => {
      if (res.code === "200") {
        const rawList = res.data;
        console.log("售后历史列表：", rawList);

        afterSalesHistoryList.value = Array.isArray(rawList) ? rawList : [];

        if (afterSalesHistoryList.value.length === 0) {
          ElMessage({
            message: $t("myorder.messages.noHistoryRecords"),
            type: "warning",
          });
          return;
        }

        showHistoryDialog.value = true;
      } else {
        ElMessage({
          message: $t("myorder.messages.getHistoryFailed") + res.msg,
          type: "error",
        });
      }
    })
    .catch((err) => {
      console.error(err);
      ElMessage({
        message: $t("myorder.messages.getHistoryError"),
        type: "error",
      });
    });
};

const viewApplicationDetail = (applyId) => {
  if (!applyId || applyId === "undefined") {
    ElMessage({
      message: $t("myorder.messages.invalidApplyId"),
      type: "error",
    });
    return;
  }

  request
    .get(`/aftersale/detail/${applyId}`)
    .then((res) => {
      if (res.code === "200") {
        const data = res.data;

        console.log("详情数据:", data);

        currentApplication.saleType = data.saleType;
        currentApplication.title = data.productTitle;
        currentApplication.description = data.productDescription;
        currentApplication.evidence = data.productImages
          ? data.productImages.split(",").map((url) => ({ url }))
          : [];

        updateStatusByCode(data.applicationStatus, data.resultType);
        showStatusDialog.value = true;
      } else {
        ElMessage({
          message: $t("myorder.messages.getDetailFailed") + res.msg,
          type: "error",
        });
      }
    })
    .catch((err) => {
      console.error(err);
      ElMessage({
        message: $t("myorder.messages.getDetailError"),
        type: "error",
      });
    });
};

onMounted(() => {
  fetchOrders(); // 页面加载时获取订单数据
  const status = route.query.status;
  if (status) {
    currentStatus.value = status;
  }
});
</script>
